<template>
  <div class="teacher-management">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="教师姓名">
          <el-input v-model="searchForm.name" placeholder="输入教师姓名" clearable />
        </el-form-item>
        <el-form-item label="专长乐器">
          <el-select 
            v-model="searchForm.instruments" 
            multiple
            placeholder="全部乐器" 
            clearable
            style="width: 200px"
            popper-class="teacher-select-dropdown"
          >
            <el-option 
              v-for="item in instrumentsOptions"
              :key="item.id"
              :label="item.icName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="全部状态" 
            clearable
            style="width: 200px"
            popper-class="teacher-select-dropdown"
          >
            <el-option 
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons" v-permission="['editTeacher']">
      <el-button type="primary" @click="showEditDialog('add')">
        <el-icon><Plus /></el-icon>新增教师
      </el-button>
      <!-- <el-button @click="handleImport">
        <el-icon><Upload /></el-icon>批量导入
      </el-button>
      <el-button @click="handleExport">
        <el-icon><Download /></el-icon>导出数据
      </el-button> -->
    </div>

    <!-- 教师列表 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="filteredTeachers" style="width: 100%" v-loading="loading">
        <el-table-column label="头像" width="80">
          <template #default="{row}">
            <el-avatar :size="40" :src="row.avatar || defaultAvatar" />
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" label="姓名" width="120" sortable />
        <el-table-column prop="gender" label="性别">
          <template #default="{row}">
            <el-tag :type="row.gender == 1 ? 'info' : 'danger'" size="small">
              {{ row.gender == 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" width="150" />
        <el-table-column prop="instruments" label="专长乐器" width="180">
          <template #default="{row}">
            <div style="display: flex; flex-wrap: wrap; gap: 4px;">
              <el-tag 
                v-for="inst in row.instruments" 
                :key="inst" 
                size="small"
              >
                {{ formatInstrument(inst) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="教学级别" width="120">
          <template #default="{row}">
            {{ 
              row.level == 1 ? '初级教师' : 
              row.level == 2 ? '中级教师' : 
              row.level == 3 ? '高级教师' : '特级教师' 
            }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.status == 1 ? 'success' : 'info'">
              {{ row.status == 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" v-permission="['editTeacher']">
          <template #default="{row}">
            <el-button type="primary" link size="small" @click="showDetailDialog(row)">详情</el-button>
            <el-button type="primary" link size="small" @click="showEditDialog('edit', row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 教师编辑对话框 -->
    <teacher-edit
      v-model="editVisible"
      :teacher-data="currentTeacher"
      :mode="editMode"
      :instrumentsOptions="instrumentsOptions"
      @success="handleEditSuccess"
    />

    <!-- 教师详情对话框 -->
    <teacher-detail
      v-model="detailVisible"
      :teacher-data="currentTeacher"
      :instrumentsOptions="instrumentsOptions"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, ArrowDown } from '@element-plus/icons-vue'
import { getTeachers, insertTeacher, updateTeacher, deleteTeacher } from '@/api/teacher'
import TeacherEdit from './TeacherEdit.vue'
import TeacherDetail from './TeacherDetail.vue'
import {getInstrumentList} from '@/api/instrument.js'

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const instrumentsOptions = ref([])
getInstrumentList().then(res => {
  instrumentsOptions.value = res.data
})
// 搜索表单
const searchForm = reactive({
  name: '',
  instruments: [],
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 教师列表数据
const teachers = ref([])

const loading = ref(false)

// 对话框控制
const editVisible = ref(false)
const detailVisible = ref(false)
const scheduleVisible = ref(false)
const currentTeacher = ref(null)
const currentTeacherId = ref('')
const editMode = ref('add') // 'add' or 'edit'

// 获取教师列表
const fetchTeachers = async () => {
  loading.value = true
  try {
    const res = await getTeachers({
      page: pagination.current,
      pageSize: pagination.size,
      keyword: searchForm.name,
      status: searchForm.status === 1 ? 'active' : searchForm.status === 0 ? 'inactive' : ''
    })
    
    if (res.code === 200) {
      teachers.value = res.data.list.map(item => ({
        ...item,
        instruments: item.instrumentIds
      }))
      pagination.total = res.data.total
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索教师
const handleSearch = () => {
  pagination.current = 1
  fetchTeachers()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.instrument = ''
  searchForm.status = ''
  handleSearch()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchTeachers()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchTeachers()
}

// 显示编辑对话框
const showEditDialog = (mode, teacher = null) => {
  editMode.value = mode
  currentTeacher.value = teacher ? { ...teacher } : null
  editVisible.value = true
}

// 显示详情对话框
const showDetailDialog = (teacher) => {
  currentTeacher.value = { ...teacher }
  detailVisible.value = true
}


// 导入
const handleImport = () => {
  ElMessage.info('批量导入功能')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出数据功能')
}

// 编辑成功回调
const handleEditSuccess = (formData) => {
  if (editMode.value === 'add') {
    insertTeacher(formData).then(() => {
      ElMessage.success('新增教师成功')
      fetchTeachers()
    }).catch(() => {
      ElMessage.error('新增教师失败')
    })
  } else {
    updateTeacher(formData).then(() => {
      ElMessage.success('更新教师信息成功')
      fetchTeachers()
    }).catch(() => {
      ElMessage.error('更新教师信息失败')
    })
  }
}


// 状态选项
const statusOptions = [
  { value: '1', label: '在职' },
  { value: '0', label: '离职' }
]

// 格式化乐器名称
const formatInstrument = (instrument) => {
  const found = instrumentsOptions.value.find(item => item.id === instrument)
  return found ? found.icName : instrument
}

// 过滤教师列表
const filteredTeachers = computed(() => {
  // 使用真实数据时，后端已处理过滤，直接返回全部数据
  return teachers.value
})

// 初始化加载数据
onMounted(() => {
  fetchTeachers()
})
</script>

<style scoped>
.teacher-management {
  padding: 20px;
}

/* 修复下拉框被遮挡问题 */
:deep(.teacher-select-dropdown) {
  z-index: 9999 !important;
}

.search-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
